<template>
  <div class="finance-modern-root">
    <el-card class="modern-card search-card-modern">
      <el-row :gutter="16" class="search-row-modern">
        <el-col :span="6">
          <el-input v-model="searchForm.orderNumber" placeholder="订单编号" clearable prefix-icon="el-icon-search"
            class="modern-input" />
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.incomeType" placeholder="收入类型" clearable class="modern-input">
            <el-option label="全部" value="" />
            <el-option label="商品销售" value="商品销售" />
            <el-option label="服务收费" value="服务收费" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker v-model="searchForm.transactionDate" type="daterange" range-separator="至"
            start-placeholder="开始日期" end-placeholder="结束日期" class="modern-input" style="width: 250px" />
        </el-col>
        <el-col :span="6">
          <el-input v-model="searchForm.customerName" placeholder="客户名称" clearable prefix-icon="el-icon-user"
            class="modern-input" />
        </el-col>
      </el-row>
      <div class="search-buttons-modern">
        <el-button type="primary" class="modern-btn-main" @click="handleSearch"><i class="el-icon-search"></i>
          查询</el-button>
        <el-button class="modern-btn-sub" @click="resetSearch"><i class="el-icon-refresh-right"></i> 重置</el-button>
        <el-button type="success" class="modern-btn-export" @click="() => { }"><i class="el-icon-download"></i>
          导出报表</el-button>
      </div>
    </el-card>
    <el-row :gutter="24" class="stats-row-modern">
      <el-col :span="6">
        <el-card class="stats-card-modern stats-green">
          <div class="stats-content-modern">
            <div class="stats-amount-modern">¥{{ formatAmount(todayIncome) }}</div>
            <div class="stats-title-modern">今日收入</div>
            <div class="stats-trend-badge stats-green-bg"><i class="el-icon-caret-top"></i> {{ todayIncomeChange > 0 ?
              '+' + todayIncomeChange : todayIncomeChange }}% <span>较昨日</span></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card-modern stats-blue">
          <div class="stats-content-modern">
            <div class="stats-amount-modern">¥{{ formatAmount(thisMonthIncome) }}</div>
            <div class="stats-title-modern">本月收入</div>
            <div class="stats-trend-badge stats-blue-bg"><i class="el-icon-caret-top"></i> {{ thisMonthIncomeChange > 0
              ? '+' + thisMonthIncomeChange : thisMonthIncomeChange }}% <span>较上月</span></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card-modern stats-purple">
          <div class="stats-content-modern">
            <div class="stats-amount-modern">¥{{ formatAmount(incomeByType['商品销售']) }}</div>
            <div class="stats-title-modern">商品销售</div>
            <div class="stats-trend-badge stats-purple-bg"><i class="el-icon-percent"></i> {{
              getPercentage(incomeByType['商品销售'], totalIncome) }}% <span>占总收入</span></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card-modern stats-orange">
          <div class="stats-content-modern">
            <div class="stats-amount-modern">¥{{ formatAmount(incomeByType['服务收费']) }}</div>
            <div class="stats-title-modern">服务收费</div>
            <div class="stats-trend-badge stats-orange-bg"><i class="el-icon-percent"></i> {{
              getPercentage(incomeByType['服务收费'], totalIncome) }}% <span>占总收入</span></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-card class="modern-card table-card-modern">
      <el-table :data="displayIncomeRecords" stripe class="modern-table" v-loading="loading">
        <el-table-column prop="orderNumber" label="订单编号" width="180" />
        <el-table-column prop="incomeType" label="收入类型" width="120" />
        <el-table-column prop="customerName" label="客户名称" width="120" />
        <el-table-column prop="employeeName" label="工作人员" width="120" />
        <el-table-column label="交易金额" width="120">
          <template #default="scope">¥{{ scope.row.amount ? scope.row.amount.toFixed(2) : '0.00' }}</template>
        </el-table-column>
        <el-table-column prop="transactionDate" label="交易日期" width="140">
          <template #default="scope">
            {{ formatDate(scope.row.transactionDate) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.orderStatus === '已完成' ? 'success' : 'info'" size="small">{{ scope.row.orderStatus
              }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" class="modern-btn-main" @click="openEditDialog(scope.row)"><i
                class="el-icon-edit"></i> 编辑</el-button>
            <el-button type="danger" size="small" class="modern-btn-danger" @click="handleDelete(scope.row)"><i
                class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container-modern">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper" :total="filteredIncomeRecords.length"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 编辑收入弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑收入记录" width="500px" :before-close="handleDialogClose">
      <el-form ref="financeFormRef" :model="editForm" :rules="editRules" label-width="100px">
        <!-- 订单编号 -->
        <el-form-item label="订单编号" prop="orderNumber">
          <el-input v-model="editForm.orderNumber" disabled />
        </el-form-item>
        <!-- 收入类型 -->
        <el-form-item label="收入类型" prop="incomeType">
          <el-select v-model="editForm.incomeType" placeholder="请选择收入类型" style="width: 100%">
            <el-option label="商品销售" value="商品销售" />
            <el-option label="服务收费" value="服务收费" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <!-- 客户名称 -->
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="editForm.customerName" placeholder="请输入客户名称" />
        </el-form-item>
        <!-- 工作人员 -->
        <el-form-item label="工作人员" prop="employeeName">
          <el-input v-model="editForm.employeeName" placeholder="请输入工作人员姓名" />
        </el-form-item>
        <!-- 交易金额 -->
        <el-form-item label="交易金额" prop="amount">
          <el-input v-model.number="editForm.amount" placeholder="请输入交易金额" prefix-icon="el-icon-money">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <!-- 交易日期 -->
        <el-form-item label="交易日期" prop="transactionDate">
          <el-date-picker v-model="editForm.transactionDate" type="date" placeholder="请选择交易日期" style="width: 100%" />
        </el-form-item>
        <!-- 订单状态 -->
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="editForm.orderStatus" placeholder="请选择订单状态" style="width: 100%">
            <el-option label="已完成" value="已完成" />
            <el-option label="已退款" value="已退款" />
          </el-select>
        </el-form-item>
        <!-- 备注信息 -->
        <el-form-item label="备注信息" prop="note">
          <el-input v-model="editForm.note" type="textarea" :rows="3" placeholder="请输入备注信息（可选）" />
        </el-form-item>
      </el-form>
      <!-- 弹窗底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import dayjs from 'dayjs'
import { useOrderStore } from '../stores/orderStore'
import { useProductOrderStore } from '../stores/productOrderStore'

// 初始化全局Pinia store
const orderStore = useOrderStore()
const productOrderStore = useProductOrderStore()

// 收入记录数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const editDialogVisible = ref(false)
const editForm = ref({})
const financeFormRef = ref(null)

const searchForm = ref({
  orderNumber: '',
  incomeType: '',
  transactionDate: [],
  customerName: ''
})

// 快速搜索关键词
const searchKeyword = ref('')

// 对话框状态
const addDialogVisible = ref(false)

// 表单数据
const addForm = ref({
  orderNumber: '',
  incomeType: '商品销售',
  customerName: '',
  employeeName: '',
  petName: '',
  amount: 0,
  transactionDate: dayjs().format('YYYY-MM-DD'),
  paymentMethod: '微信',
  orderStatus: '已完成',
  note: ''
})


const editRules = ref({
  orderNumber: [
    { required: true, message: '请输入订单编号', trigger: 'blur' }
  ],
  incomeType: [
    { required: true, message: '请选择收入类型', trigger: 'change' }
  ],
  customerName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入交易金额', trigger: 'blur' },
    { type: 'number', message: '交易金额必须为数字', trigger: 'blur' },
    { validator: (rule, value) => value > 0 || '交易金额必须大于0', trigger: 'blur' }
  ],
  transactionDate: [
    { required: true, message: '请选择交易日期', trigger: 'change' }
  ]
})

// 合并两类订单，统一字段
const allOrders = computed(() => {
  console.log('orderStore.orders:', orderStore.orders)
  console.log('productOrderStore.orders:', productOrderStore.orders)
  const normalize = (order, type) => ({
    id: order.id,
    orderNumber: order.orderNumber || order.id,
    incomeType: order.incomeType || (type === 'product' ? '商品销售' : '服务收费'),
    customerName: order.customerName,
    employeeName: order.employeeName,
    amount: order.actualAmount||order.totalAmount,
    // 兼容不同字段名
    transactionDate: order.transactionDate || dayjs(order.createdAt).format('YYYY-MM-DD') ||  '',
    orderStatus: order.orderStatus || order.status || '',
    note: order.note || '',
    sourceType: type
  })
  const productOrders = productOrderStore.orders.map(o => normalize(o, 'product'))
  const serviceOrders = orderStore.orders.map(o => normalize(o, 'service'))
  const merged = [...productOrders, ...serviceOrders]
  console.log('allOrders merged:', merged)
  return merged
})

const incomeRecords = allOrders

// 计算属性：过滤后的收入记录
const filteredIncomeRecords = computed(() => {
  let records = [...incomeRecords.value]

  // 搜索表单过滤
  if (searchForm.value.orderNumber) {
    records = records.filter(record =>
      record.orderNumber.includes(searchForm.value.orderNumber)
    )
  }

  if (searchForm.value.incomeType) {
    records = records.filter(record =>
      record.incomeType === searchForm.value.incomeType
    )
  }

  if (searchForm.value.customerName) {
    records = records.filter(record =>
      record.customerName.includes(searchForm.value.customerName)
    )
  }

  if (searchForm.value.transactionDate && searchForm.value.transactionDate.length === 2) {
    let [startDate, endDate] = searchForm.value.transactionDate;
    startDate = dayjs(startDate).format('YYYY-MM-DD');
    endDate = dayjs(endDate).format('YYYY-MM-DD');
    records = records.filter(record => {
      return record.transactionDate >= startDate && record.transactionDate <= endDate;
    });
  }

  // 快速搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    records = records.filter(record =>
      record.orderNumber.toLowerCase().includes(keyword) ||
      record.customerName.toLowerCase().includes(keyword)
    )
  }

  return records
})

// 计算属性：当前页显示的收入记录
const displayIncomeRecords = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredIncomeRecords.value.slice(start, end)
})

// 计算属性：统计数据
const today = dayjs().format('YYYY-MM-DD')
const yesterday = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
const firstDayOfMonth = dayjs().startOf('month').format('YYYY-MM-DD')
const lastDayOfMonth = dayjs().endOf('month').format('YYYY-MM-DD')
const firstDayOfLastMonth = dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD')
const lastDayOfLastMonth = dayjs().subtract(1, 'month').endOf('month').format('YYYY-MM-DD')

// 今日收入
const todayIncome = computed(() => {
  return incomeRecords.value.filter(record => formatDate(record.transactionDate) === today)
    .reduce((sum, record) => sum + (Number(record.amount) || 0), 0)
})

// 昨日收入
const yesterdayIncome = computed(() => {
  return incomeRecords.value.filter(record => formatDate(record.transactionDate) === yesterday)
    .reduce((sum, record) => sum + (Number(record.amount) || 0), 0)
})

// 本月收入
const thisMonthIncome = computed(() => {
  return incomeRecords.value.filter(record => {
    const d = formatDate(record.transactionDate)
    return d >= firstDayOfMonth && d <= lastDayOfMonth
  }).reduce((sum, record) => sum + (Number(record.amount) || 0), 0)
})

// 上月收入
const lastMonthIncome = computed(() => {
  return incomeRecords.value.filter(record => {
    const d = formatDate(record.transactionDate)
    return d >= firstDayOfLastMonth && d <= lastDayOfLastMonth
  }).reduce((sum, record) => sum + (Number(record.amount) || 0), 0)
})

// 今日收入变化百分比
const todayIncomeChange = computed(() => {
  if (yesterdayIncome.value === 0) return 0
  return ((todayIncome.value - yesterdayIncome.value) / yesterdayIncome.value * 100).toFixed(1)
})

// 本月收入变化百分比
const thisMonthIncomeChange = computed(() => {
  if (lastMonthIncome.value === 0) return 0
  return ((thisMonthIncome.value - lastMonthIncome.value) / lastMonthIncome.value * 100).toFixed(1)
})

// 按类型分类的收入
const incomeByType = computed(() => {
  const result = {
    '商品销售': 0,
    '服务收费': 0,
    '会员充值': 0,
    '其他': 0
  }
  incomeRecords.value.forEach(record => {
    if (result[record.incomeType] !== undefined) {
      result[record.incomeType] += Number(record.amount) || 0
    }
  })
  return result
})

// 总收入
const totalIncome = computed(() => {
  return incomeRecords.value.reduce((sum, record) => sum + (Number(record.amount) || 0), 0)
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
  loading.value = true

  // 模拟API请求延迟
  setTimeout(() => {
    loading.value = false
    ElMessage({
      message: '搜索完成',
      type: 'success',
      duration: 1500
    })
  }, 500)
}

const resetSearch = () => {
  searchForm.value = {
    orderNumber: '',
    incomeType: '',
    transactionDate: [],
    customerName: ''
  }
  searchKeyword.value = ''
  currentPage.value = 1
}

const handleQuickSearch = () => {
  currentPage.value = 1
}

const openEditDialog = (record) => {
  // 复制记录数据到编辑表单
  editForm.value = { ...record }

  editDialogVisible.value = true

  // 延迟聚焦第一个可编辑输入框
  nextTick(() => {
    const firstEditableInput = document.querySelector('.el-dialog input:not([disabled])')
    if (firstEditableInput) firstEditableInput.focus()
  })
}

const handleDialogClose = () => {
  // 重置表单验证状态
  if (financeFormRef.value) {
    financeFormRef.value.resetFields()
  }

  addDialogVisible.value = false
  editDialogVisible.value = false
}

const submitAddForm = () => {
  financeFormRef.value.validate((valid) => {
    if (!valid) return false

    // 检查交易日期是否大于今天
    const transactionDate = dayjs(addForm.value.transactionDate)
    const today = dayjs()

    if (transactionDate.isAfter(today)) {
      ElMessage({
        message: '交易日期不能大于今天',
        type: 'error'
      })
      return
    }

    // 添加新记录
    const newRecord = {
      ...addForm.value,
      id: addForm.value.orderNumber // 使用订单编号作为唯一标识
    }

    orderStore.addOrder(newRecord)

    // 关闭对话框
    addDialogVisible.value = false

    // 提示成功
    ElMessage({
      message: '收入记录添加成功',
      type: 'success',
      duration: 2000
    })
  })
}

const submitEditForm = () => {
  financeFormRef.value.validate((valid) => {
    if (!valid) return false

    // 检查交易日期是否大于今天
    const transactionDate = dayjs(editForm.value.transactionDate)
    const today = dayjs()

    if (transactionDate.isAfter(today)) {
      ElMessage({
        message: '交易日期不能大于今天',
        type: 'error'
      })
      return
    }

    // 更新记录
    const index = incomeRecords.value.findIndex(
      record => record.id === editForm.value.id
    )

    if (index !== -1) {
      orderStore.updateOrder(index, { ...editForm.value })

      // 关闭对话框
      editDialogVisible.value = false

      // 提示成功
      ElMessage({
        message: '收入记录更新成功',
        type: 'success',
        duration: 2000
      })
    }
  })
}

const handleDelete = (record) => {
  ElMessageBox.confirm(
    `确定要删除订单 ${record.orderNumber} 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 从数组中删除记录
    const index = incomeRecords.value.findIndex(item => item.id === record.id)

    if (index !== -1) {
      orderStore.deleteOrder(index)

      ElMessage({
        message: '收入记录已删除',
        type: 'success',
        duration: 2000
      })
    }
  }).catch(() => {
    // 取消删除
  })
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

// 格式化金额为千分位
const formatAmount = (amount) => {
  const num = Number(amount) || 0
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 计算百分比（保留一位小数）
const getPercentage = (value, total) => {
  if (total === 0) return 0
  return ((value / total) * 100).toFixed(1)
}

// 格式化日期为 YYYY-MM-DD
const formatDate = (date) => {
  if (!date) return ''
  // 支持 2025,7,5 这种格式
  if (typeof date === 'string' && date.includes(',')) {
    const parts = date.split(',').map(s => s.trim())
    if (parts.length === 3) {
      const [y, m, d] = parts
      return dayjs(`${y}-${m.padStart(2, '0')}-${d.padStart(2, '0')}`).format('YYYY-MM-DD')
    }
  }
  // 支持时间戳
  if (typeof date === 'number') {
    return dayjs(date).format('YYYY-MM-DD')
  }
  // 支持 20250705 纯数字字符串
  if (typeof date === 'string' && /^\d{8}$/.test(date)) {
    return dayjs(date.substr(0,4)+'-'+date.substr(4,2)+'-'+date.substr(6,2)).format('YYYY-MM-DD')
  }
  // 其他情况直接用 dayjs 解析
  return dayjs(date).isValid() ? dayjs(date).format('YYYY-MM-DD') : ''
}

// 组件挂载时初始化数据
onMounted(async () => {
  loading.value = true
  console.log('onMounted: fetching orders...')
  const [orderRes, productOrderRes] = await Promise.all([
    orderStore.fetchOrders().then(res => { console.log('orderStore.fetchOrders result:', res); return res }),
    productOrderStore.fetchOrders().then(res => { console.log('productOrderStore.fetchOrders result:', res); return res })
  ])
  loading.value = false
  console.log('onMounted: fetch complete')

  // 设置默认日期范围为近7天
  // searchForm.value.transactionDate = [
  //   dayjs().subtract(6, 'day').format('YYYY-MM-DD'),
  //   dayjs().format('YYYY-MM-DD')
  // ]
})

const phoneRules = [
  { required: true, message: '请输入手机号', trigger: 'blur' },
  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
];
const emailRules = [
  { required: true, message: '请输入邮箱', trigger: 'blur' },
  { pattern: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/, message: '邮箱格式不正确', trigger: 'blur' }
];
</script>

<style scoped>
.finance-modern-root {
  padding: 40px 32px;
  background: #f7f9fb;
  min-height: 100vh;
}

.finance-header-modern {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.modern-btn-main {
  border-radius: 10px;
  font-weight: 600;
  background: #2563eb;
  border: none;
  color: #fff;
  transition: background 0.2s;
}

.modern-btn-main:hover {
  background: #1d4ed8;
}

.modern-btn-sub {
  border-radius: 10px;
  font-weight: 500;
  background: #f3f4f6;
  color: #374151;
  border: none;
}

.modern-btn-sub:hover {
  background: #e5e7eb;
}

.modern-btn-export {
  border-radius: 10px;
  font-weight: 500;
  background: #22c55e;
  color: #fff;
  border: none;
}

.modern-btn-export:hover {
  background: #16a34a;
}

.search-card-modern {
  margin-bottom: 28px;
  border-radius: 16px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
  border: none;
  padding: 18px 18px 8px 18px;
}

.search-row-modern {
  margin-bottom: 0;
}

.search-buttons-modern {
  margin-top: 14px;
  display: flex;
  gap: 14px;
}

.stats-row-modern {
  margin-bottom: 28px;
}

.stats-card-modern {
  border-radius: 16px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
  border: none;
  padding: 0;
}

.stats-content-modern {
  padding: 30px 0 18px 0;
  text-align: center;
}

.stats-title-modern {
  font-size: 14px;
  font-weight: 400;
  color: #7b8191;
  margin-bottom: 0;
  margin-top: 8px;
}

.stats-amount-modern {
  font-size: 36px;
  font-weight: bold;
  color: #22223b;
  margin-bottom: 0;
}

.stats-trend-badge {
  display: inline-block;
  border-radius: 12px;
  padding: 2px 12px;
  font-size: 13px;
  font-weight: 500;
  margin-top: 10px;
  background: #f3f4f6;
}

.stats-green-bg {
  background: #e0fbe6;
  color: #22c55e;
}

.stats-blue-bg {
  background: #e0e7ff;
  color: #2563eb;
}

.stats-purple-bg {
  background: #f3e8ff;
  color: #a21caf;
}

.stats-orange-bg {
  background: #ffedd5;
  color: #ea580c;
}

.table-card-modern {
  margin-top: 28px;
  border-radius: 16px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
  border: none;
  padding: 0 0 10px 0;
}

.table-actions-modern {
  display: flex;
  align-items: center;
  padding: 18px 0 0 0;
  border-bottom: 1px solid #f0f1f3;
  margin-bottom: 0;
}

.modern-table {
  border-radius: 12px;
  overflow: hidden;
  font-size: 15px;
}

.modern-table .el-table__header th {
  background: #f9fafb;
  font-weight: 600;
  color: #374151;
  border-bottom: 1.5px solid #e5e7eb;
}

.modern-table .el-table__row:hover td {
  background: #f1f5f9;
}

.modern-table .el-table__cell {
  border-bottom: 1px solid #f3f4f6;
}

.modern-table .el-button {
  border-radius: 8px !important;
}

.modern-btn-danger {
  border-radius: 10px;
  font-weight: 500;
  background: #f87171;
  color: #fff;
  border: none;
}

.modern-btn-danger:hover {
  background: #ef4444;
}

.pagination-container-modern {
  margin-top: 18px;
  text-align: right;
}

.modern-input {
  border-radius: 8px;
  font-size: 15px;
}
</style>
